package xin.fsqr520.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xin.fsqr520.project.domain.po.Card;
import xin.fsqr520.project.domain.po.CardConsumeRecord;
import xin.fsqr520.project.domain.vo.CardConsumeSummaryVO;
import xin.fsqr520.project.domain.vo.ConsumeDateGroupVO;
import xin.fsqr520.project.domain.vo.ConsumeRecordVO;
import xin.fsqr520.project.domain.vo.Result;
import xin.fsqr520.project.mapper.CardConsumeRecordMapper;
import xin.fsqr520.project.mapper.CardMapper;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/card")
@Slf4j
public class CardController {

    @Autowired
    private CardMapper cardMapper;

    @Autowired
    private CardConsumeRecordMapper cardConsumeRecordMapper;


    @PostMapping("/bindcard")
    public Result<?> bindcard(@RequestBody Card card) {
        if (card == null || card.getCardId() == null || card.getUserId() == null || card.getPassword() == null)
            return Result.error("信息不完善 无法注册");
        Card card1 = cardMapper.selectOne(new LambdaQueryWrapper<Card>().eq(Card::getCardId, card.getCardId()));
        if (card1 != null) return Result.error("当前卡号已使用");
        Card card2 = cardMapper.selectOne(new LambdaQueryWrapper<Card>().eq(Card::getUserId, card.getUserId()));
        if (card2 != null) return Result.error("当前用户已绑定校园卡");

        int i = cardMapper.insert(card);
        if(i==1) return Result.success("注册成功");
        return Result.error("注册失败");

    }

    @GetMapping("/getCardInfo")
    public Result<?> getCardInfo(Long userId) {
        // 查询卡余额、累计充值和消费
        Card card = cardMapper.selectOne(
                new LambdaQueryWrapper<Card>()
                        .eq(Card::getUserId, userId)
                        .select(Card::getBalance, Card::getTotalRecharge,
                                Card::getTotalConsumption, Card::getCardId)
        );
        if (card == null) {
            return Result.error("找不到用户校园卡信息");
        }

        // 构建返回VO
        CardConsumeSummaryVO summary = CardConsumeSummaryVO.builder()
                .cardBalance(card.getBalance())
                .totalRecharge(card.getTotalRecharge())
                .totalConsumption(card.getTotalConsumption())
                .build();

        // 查询消费记录
        List<CardConsumeRecord> records = cardConsumeRecordMapper.selectList(
                new LambdaQueryWrapper<CardConsumeRecord>()
                        .eq(CardConsumeRecord::getCardId, card.getCardId())
                        .select(CardConsumeRecord::getConsumeTime,
                                CardConsumeRecord::getConsumeAmount,
                                CardConsumeRecord::getMerchantName)
                        .orderByDesc(CardConsumeRecord::getConsumeTime)
        );

        if (records.isEmpty()) {
            summary.setConsumeGroups(new ArrayList<>());
            return Result.success(summary);
        }

        // 处理分组逻辑
        List<ConsumeDateGroupVO> groups = new ArrayList<>();
        List<ConsumeRecordVO> dayRecords = new ArrayList<>();
        LocalDate currentDate = records.get(0).getConsumeTime().toLocalDate();
        BigDecimal dayTotal = BigDecimal.ZERO;

        for (CardConsumeRecord record : records) {
            LocalDate recordDate = record.getConsumeTime().toLocalDate();

            // 日期不同时，封装上一组数据
            if (!recordDate.equals(currentDate)) {
                groups.add(new ConsumeDateGroupVO(
                        currentDate.format(DateTimeFormatter.ofPattern("MM月dd日")),
                        dayTotal,
                        new ArrayList<>(dayRecords) // 注意创建新集合，避免引用问题
                ));

                // 重置分组变量
                currentDate = recordDate;
                dayTotal = BigDecimal.ZERO;
                dayRecords.clear();
            }

            // 累加当日数据
            dayTotal = dayTotal.add(record.getConsumeAmount());
            dayRecords.add(new ConsumeRecordVO(
                    record.getMerchantName(),
                    record.getConsumeAmount()
            ));
        }

        // 处理最后一组数据（关键修复）
        groups.add(new ConsumeDateGroupVO(
                currentDate.format(DateTimeFormatter.ofPattern("MM月dd日")),
                dayTotal,
                dayRecords
        ));

        summary.setConsumeGroups(groups);
        return Result.success(summary);
    }


    @PutMapping("/updateBalance")
    public Result<?> updateCardBalance(@RequestBody Map<String, Object> params) {
        try {
            // 1. 安全获取 userId 并转换为 Long
            Object userIdObj = params.get("userId");
            if (userIdObj == null) {
                return Result.error("userId 不能为空");
            }
            Long userId;
            if (userIdObj instanceof Number) {
                // 处理数字类型（Integer/Long等）
                userId = ((Number) userIdObj).longValue();
            } else if (userIdObj instanceof String) {
                // 处理字符串类型（如前端传字符串格式的数字）
                userId = Long.parseLong((String) userIdObj);
            } else {
                return Result.error("userId 格式错误");
            }

            // 2. 安全获取 balance 并转换为 BigDecimal（金额建议用 BigDecimal）
            Object balanceObj = params.get("balance");
            if (balanceObj == null) {
                return Result.error("balance 不能为空");
            }
            BigDecimal balance;
            if (balanceObj instanceof Number) {
                // 处理数字类型（Integer/Double等）
                balance = new BigDecimal(balanceObj.toString());
            } else if (balanceObj instanceof String) {
                // 处理字符串类型（如 "100.00"）
                balance = new BigDecimal((String) balanceObj);
            } else {
                return Result.error("balance 格式错误");
            }

            // 3. 校验金额必须为正数
            if (balance.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("充值金额必须大于0");
            }

            // 4. 执行充值业务
            log.info("接收充值请求：userId={}, balance={}", userId, balance);
            int i = cardMapper.addBalanceByUserId(userId, balance);
            if (i == 1) return Result.success("充值成功");
            return Result.success("充值失败");

        } catch (NumberFormatException e) {
            return Result.error("数字格式错误：" + e.getMessage());
        } catch (Exception e) {
            log.error("充值异常", e);
            return Result.error("系统异常，请稍后重试");
        }
    }

}
